<template>
  <el-dialog v-model="visible" :title="`选择${typePrefix}评论`" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.noteId" :placeholder="noteIdPlaceholder" class="handle-input mr10" clearable />
      <el-input v-model="searchForm.noteTitle" :placeholder="noteTitlePlaceholder" class="handle-input mr10"
        clearable />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="replyTable" header-cell-class-name="table-header"
      @row-click="handleRowClick" row-key="replyId">
      <el-table-column type="radio" width="55">
        <template #default="scope">
          <el-radio v-model="selectedReply" :label="scope.row.replyId"
            @change="handleRadioChange(scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="replyId" label="评论ID" width="120" />
      <el-table-column prop="authorAvatar" label="回复者头像" width="80" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.avatarUrl" :src="scope.row.avatarUrl"
            style="width:40px;height:40px;border-radius:50%;" fit="cover" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="authorInfo" label="回复者昵称/ID" min-width="150">
        <template #default="scope">
          {{ scope.row.authorName }} / {{ scope.row.authorId }}
        </template>
      </el-table-column>
      <el-table-column prop="parentAuthorAvatar" label="被回复者头像" width="80" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.parentAuthorAvatar" :src="scope.row.parentAuthorAvatar"
            style="width:40px;height:40px;border-radius:50%;" fit="cover" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="parentAuthorInfo" label="被回复者昵称/ID" min-width="150">
        <template #default="scope">
          <span v-if="scope.row.parentAuthorName">{{ scope.row.parentAuthorName }} / {{ scope.row.parentAuthorId
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="replyContent" label="回复内容" min-width="200">
        <template #default="scope">
          <!-- 优先显示文本内容 -->
          <div v-if="scope.row.replayContent && scope.row.replayContent.trim()" class="content-cell">
            {{ scope.row.replayContent }}
          </div>
          <!-- 没有文本内容时显示图片 -->
          <div v-else-if="scope.row.replayImgUrl" class="image-content">
            <el-image :src="scope.row.replayImgUrl" style="width:60px;height:60px;border-radius:4px;" fit="cover"
              :preview-src-list="[scope.row.replayImgUrl]" />
          </div>
          <!-- 都没有时显示 - -->
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="authorReplay" label="是否作者" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.authorReplay === 1 ? 'success' : 'info'">
            {{ scope.row.authorReplay === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="replayStatus" label="是否折叠" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.replayStatus === 1 ? 'warning' : 'success'">
            {{ scope.row.replayStatus === 1 ? '已折叠' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ dateFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">{{ selectedReplyData ? `已选择：${selectedReplyData.replayContent || '图片评论'}` :
          `未选择${typePrefix}评论` }}</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { getBlogReplies, getForumReplies } from "@/api/content";

export default {
  name: "SelectReply",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 动态/帖子ID，用来筛选评论
    noteId: {
      type: [String, Number],
      default: "",
      required: false
    },
    // 类型：'blog' 动态 或 'forum' 帖子
    replyType: {
      type: String,
      default: 'blog',
      validator: (value) => ['blog', 'forum'].includes(value)
    },
    // 已选中的评论数据
    selectedData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        noteId: "",
        noteTitle: "",
      },
      tableData: [],
      selectedReply: null, // 当前选中的评论ID
      selectedReplyData: null, // 当前选中的评论完整数据
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    },
    // 根据类型获取前缀文本（动态/帖子）
    typePrefix() {
      return this.replyType === 'blog' ? '动态' : '帖子';
    },
    // 动态/帖子ID占位符
    noteIdPlaceholder() {
      return `${this.typePrefix}ID`;
    },
    // 动态/帖子标题占位符
    noteTitlePlaceholder() {
      return `${this.typePrefix}标题`;
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
        this.initSelectedData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      // 根据传入的noteId筛选评论
      if (this.noteId) {
        // 根据类型设置不同的参数名
        if (this.replyType === 'blog') {
          params.blogNoteId = this.noteId;
        } else {
          params.forumNoteId = this.noteId;
        }
      }

      // 根据搜索表单构建查询参数
      if (this.searchForm.noteId) {
        params.noteId = this.searchForm.noteId;
      }
      if (this.searchForm.noteTitle) {
        params.noteTitle = this.searchForm.noteTitle;
      }

      return params;
    },
    // 获取对应的API方法
    getApiMethod() {
      return this.replyType === 'blog' ? getBlogReplies : getForumReplies;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const apiMethod = this.getApiMethod();
        const response = await apiMethod(params);

        if (response && response.data) {
          // 将API返回的数据映射到表格需要的格式
          this.tableData = (response.data.rows || response.data).map(item => ({
            replyId: item.replyId || item.id,
            avatarUrl: item.avatarUrl || '',
            authorName: item.authorName || '',
            authorId: item.authorId || '',
            parentAuthorAvatar: item.parentAuthorAvatar || '',
            parentAuthorName: item.parentAuthorName || '',
            parentAuthorId: item.parentAuthorId || '',
            replayContent: item.replayContent || '',
            replayImgUrl: item.replayImgUrl || '',
            replayType: item.replayType || 0,
            authorReplay: item.authorReplay || 0,
            replayStatus: item.replayStatus || 0,
            parentId: item.parentId || '',
            topParentId: item.topParentId || '',
            createTime: item.createTime,
            // 保留原始数据
            _original: item
          }));

          // 更新总数
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取评论数据失败:', error);
        this.$message.error('获取评论数据失败');
      }
    },
    // 初始化已选中的数据
    initSelectedData() {
      if (this.selectedData) {
        this.selectedReply = this.selectedData.replyId;
        this.selectedReplyData = { ...this.selectedData };
      } else {
        this.selectedReply = null;
        this.selectedReplyData = null;
      }
    },
    // 处理单选变化
    handleRadioChange(row) {
      this.selectedReplyData = { ...row };
    },
    // 处理行点击
    handleRowClick(row) {
      this.selectedReply = row.replyId;
      this.selectedReplyData = { ...row };
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedReplyData);
      this.handleClose();
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.mb10 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.image-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

:deep(.el-date-editor) {
  margin-right: 10px;
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}
</style>
